<template>
<div>
  <el-button type="success" @click="add" style="color: #FFF;" color="#3134C7">新增</el-button>
    <el-table :data="tableData" style="width: 100%">
    <el-table-column  type="index" label="序号" width="100" />

    <el-table-column prop="roleName" label="角色名称" width="150" >
       <template #default="scope">
    <el-link type="primary" @click="logic.aa=true,getrowshu(scope.row),userroleget(scope.row.id)">
      {{ scope.row.roleName }}
    </el-link>
    </template>
    </el-table-column>

    <el-table-column prop="creator" label="创建人" width="120" />
    <el-table-column prop="creatorDate" label="创建日期" width="200" >
         <template #default="scope">
            {{ moment(scope.row.creatorDate).format('yyyy-MM-DD HH:mm:ss') }}
        </template>
    </el-table-column>
    <el-table-column prop="updator" label="修改人" width="120" />

     <el-table-column prop="updatorDate" label="修改日期" width="200" >
        <template #default="scope" >
             <span v-if="!scope.row.updatorDate || scope.row.updatorDate === ''"> </span>
           <span v-else> {{ moment(scope.row.updatorDate).format('yyyy-MM-DD HH:mm:ss') }}</span>
        </template>
     </el-table-column>

    <el-table-column fixed="right" label="操作" min-width="150">
      <template #default="scope">
        <el-button  type="primary"  @click="update(scope.row)" plain>
          修改
        </el-button>
        <el-button  type="danger"  @click="del(scope.row.id)" plain>删除</el-button>
        <el-button type="warning" plain  @click="logic.oper2=true,getrowshu(scope.row),userroleget(scope.row.id),treeuseget(-1)" ref="dearButton">
                        分配人员
                    </el-button>
      </template>
    </el-table-column>
  </el-table>
</div>



    <el-dialog v-model="dialogFormVisible" title="新增角色" width="1000">
<el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称：" prop="roleName">
      <el-input v-model="ruleForm.roleName" />
    </el-form-item>

   
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
     </el-dialog>


      <el-dialog v-model="dialogFormVisibles" title="修改角色" width="1000">
<el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForms"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称：" prop="roleName">
      <el-input v-model="ruleForms.roleName" />
    </el-form-item>

   
    <el-form-item>
      <el-button type="primary" @click="submitForms(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>
     </el-dialog>

     <el-dialog v-model="logic.oper2" :title="`请设置【${rowshu.roleName}】角色的员工`"  width="800" style="height: 300px;">
      
       <el-form label-width="120">

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="请选择部门" >
                          
                            <el-tree
                                style="max-width: 600px"
                                :data="data"
                                node-key="id" 
                                @node-click="handleNodeClick"
                                
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">   
                        <el-form-item label="请选择员工" >
                            <el-tree
                                style="max-width: 600px"
                                :data="treeuse"
                                ref="treeRef"
                                show-checkbox 
                                node-key="id"    
                                v-model="userroleadd.UserIds"     
                                 
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="logic.oper2=false">取消</el-button>
                <el-button type="primary" @click="adduserrole">
                确认
                </el-button>
            </div>
      
     </template>

     </el-dialog>

      <el-dialog v-model="logic.aa"   :title="`属于角色【${rowshu.roleName}】的员工如下`" width="800" style="height: 300px;">
        <table>
          <tr>
            <td>
               <el-tag  v-for="tag in tags"  closable :key="tag.uid" @close="deletetag(tag.uid)">
      {{ tag.userName }} 
    </el-tag>
   
            </td>
            <td>
               <el-form-item>
       <template v-slot="scope">
 <el-button style="margin-top: 17px;" class="button-new-tag" size="small" @click="jia()">
      +
    </el-button>
          </template>
                </el-form-item>
        </td>
    </tr>
        </table>
        

   


  

      </el-dialog>
</template>

<script lang="ts" setup>

import axios from 'axios'
import {ref,reactive,onMounted} from 'vue'
import moment from 'moment'
import type { TreeInstance } from 'element-plus'
import Read from  '@/http/Readhttp'
import Write from '@/http/Writehttp'
const tableData =ref([])
onMounted(()=>{
    getrole();
}
)
const getrole=()=>{
    Read.get("/api/Roles/GetRole").then(res=>{
        tableData.value=res.data.data;
    })
}

const dialogFormVisible = ref(false)
const dialogFormVisibles = ref(false)
const dialogFormVisibless = ref(false)
//新增
import {useCounterStore} from '@/stores/counter'
const pinia=useCounterStore();
const add=()=>{
    dialogFormVisible.value=true;
}
const update=(row:any)=>{
  dialogFormVisibles.value=true
Object.assign(ruleForms,row)
}
import { ElMessage,ElMessageBox, type FormInstance, type FormRules } from 'element-plus'



const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
id:'',
"roleName": "",
  "creator": pinia.account.UserName,
  
})

const ruleForms = reactive({
"roleName": "",
  "updator": pinia.account.UserName,
   "updatorDate": ""
})

const rules = reactive<FormRules>({
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
  ],
 
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        Write.post("/api/Roles/AddRole",ruleForm).then(res=>{
            if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            
            dialogFormVisible.value=false;
            ruleForm.roleName='';
            getrole();
        }
        else{
            ElMessage.error(res.data.msg);
        }
        })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const submitForms = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForms.updator=pinia.account.UserName;
        Write.put("/api/Roles/UpdateRole",ruleForms).then(res=>{
            if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            
            dialogFormVisibles.value=false;
            ruleForms.roleName='';
            getrole();
        }
        else{
            ElMessage.error(res.data.msg);
        }
        })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const reset=()=>{
  ruleForm.roleName=''
}

//删除
const del=(id:any)=>{
  ElMessageBox.confirm(
    '您确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      
      Write.put('/api/Roles/DelRole',{id:id})
      .then(res=>{
        if(res.data.code==200){
          ElMessage.success(res.data.msg); 
          getrole();//重新加载数据
          }else{
            ElMessage.error(res.data.msg); 
          }

      });

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作已被取消',
      })
    })
}
const data = ref([ {
        id:"1",
        label: 'IT信息部',
    },
    {
        id:"2",
        label: '人力资源部',
    },
    {
        id:"3",
        label: '财务部',
    },
    {
        id:"4",
        label: '销售部',
    },])
  
onMounted(()=>{
   treeuseget(-1)
})

const userroleadd=ref({
      "uid": "" as string,
  "rid": 0,
  UserIds:[]
})
const adduserrole=()=>{
   var sehu=treeRef.value?.getCheckedKeys(false);

    userroleadd.value.rid=rowshu.value.id
    userroleadd.value.uid = sehu?.toString() ?? ""; 

    Write.post('/api/Roles/AddUserRole',userroleadd.value).then(res=>{

        if(res.data.code==200){
            ElMessage.success(res.data.msg)
            getrole()
            logic.value.oper2=false
        }
        else{
            ElMessage.error(res.data.msg);
        }
    }) 
 
}
//#region 部门数据
const handleNodeClick = (data: any) => {
  //console.log(data.id)
  treeuseget(data.id)
}
//#region 根据部门获取用户信息树形

const treeRef = ref<TreeInstance>()

const treeuse=ref([])

const treeuseget=(ids:any)=>{

    Read.get('/api/Departments/GetDepartment',{params:{DepartmentId:ids}}).then(res=>{
        treeuse.value=res.data.datas
    })

}

//#region 获取行数据
const rowshu=ref({
     "roleName": "",
    "id": 0,
})

const getrowshu=(info:any)=>{

    rowshu.value=info

}
//#region 根据角色获取用户信息
const userroleget=(id:any)=>{

    userroleadd.value.rid=0
    userroleadd.value.uid = ""; 
    userroleadd.value.UserIds=[]

    Read.post('/api/Roles/GetUserRole',{rid:id}).then(res=>{

        if(res.data.datas.length==0){
            userroleadd.value.rid=0
            userroleadd.value.uid=""
            userroleadd.value.UserIds=[]
            treeRef.value?.setCheckedKeys([],true);
            return;
        }
        tags.value = res.data.datas;
        treeuseget(res.data.datas[0].departmentId)
        res.data.datas.forEach((user:any)=>{
           (userroleadd.value.UserIds as any[]).push(user.uid); 
        }) 
        //console.log(userroleadd.value.UserIds);
        treeRef.value?.setCheckedKeys(userroleadd.value.UserIds,true);
       
    })
     getroleuser(rowshu.value.id);
}
const logic=ref({
    "aa":false,
    "oper2":false
})


//tag标签弹出框
const getroleuser=(id:any)=>{
    Read.post('/api/Roles/GetUserRole',{rid:id}).then(res=>{
      tags.value = res.data.datas;
       getroleuser(rowshu.value.id);
    })
}
const tags=ref([{
  uid:0,
  userName:'',
  departmentId:0,
  rid:0
}])
//删除tag标签
const deletetag=(id:any)=>{

Write.put('/api/Roles/DeleteUserRole',{uid:id}).then(res=>{
  if(res.data.code==200)
{
  ElMessage.success(res.data.msg);
  getroleuser(rowshu.value.id);
}
else{
  ElMessage.error(res.data.msg);
}
})
}
const dearButton = ref(null); 
//点击tag的加号
const jia = () => {
  logic.value.oper2 = true;
  userroleget(rowshu.value.id)
  console.log(rowshu);
};
</script>
